﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using deviceManage.Models;
using deviceManage.vo;
using deviceManage.Tools;

namespace deviceManage.Controllers
{
    /// <summary>
    /// 登录控制器
    /// </summary>
    public class LoginController : Controller
    {
        private readonly DeviceCtx _context;

        public LoginController(DeviceCtx context)
        {
            _context = context;
        }

        //列表主页
        public IActionResult Index()
        {
            return View();
        }

        public AjaxResult DoLogin(string name,string password,bool rememberPass)
        {
            User user = this._context.User.SingleOrDefault (p => p.LoginName == name && p.Pass == password && p.Deleted == 0);
            if(user == null)
            {
                HttpContext.Session.SetString(WebContext.SESSION_KEY_USER_ID, "");
                HttpContext.Session.SetString(WebContext.SESSION_KEY_USER_NAME, "");
                return AjaxResult.GetError("用户名或密码错误");
            }
            else
            {
                HttpContext.Session.SetString(WebContext.SESSION_KEY_USER_ID, user.Id);
                HttpContext.Session.SetString(WebContext.SESSION_KEY_USER_NAME, user.Name);

                

                return AjaxResult.GetOK("登录成功");
            }
        }

        public IActionResult Logout()
        {
            HttpContext.Session.SetString(WebContext.SESSION_KEY_USER_ID, "");
            HttpContext.Session.SetString(WebContext.SESSION_KEY_USER_NAME, "");
            return View("index");
        }

    }
}
